from peewee import *
from datetime import datetime
from config import get_database

# Get database instance from config
database = get_database()

class BaseModel(Model):
    """Base model class that all models should inherit from"""
    
    id = AutoField(primary_key=True)
    created_at = DateTimeField(default=datetime.now)
    updated_at = DateTimeField(default=datetime.now)
    
    class Meta:
        database = database
    
    def save(self, *args, **kwargs):
        """Override save to update the updated_at field"""
        self.updated_at = datetime.now()
        return super().save(*args, **kwargs)
    
    @classmethod
    def create_table_if_not_exists(cls):
        """Create table if it doesn't exist"""
        if not cls.table_exists():
            cls.create_table()
    
    def to_dict(self):
        """Convert model instance to dictionary"""
        return {
            'id': self.id,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }